﻿using System;
using System.Collections.Generic;
using System.Xml;

/// <summary>
/// Extracts main attributes of the Artefact to place them in registry table
/// </summary>
public class TextTypeSdmx
{
    #region Properties

    public string[] arrText;
    public string ValidFrom;
    public string ValidTo;
    public bool IsFinal;

    #endregion

    #region C'tor

    public TextTypeSdmx()
    {
        Init();
    }

    private void Init()
    {
        arrText = new string[Manager.Instance.LangCount + 1];
        ArrTextInit(string.Empty);

        ValidFrom = ValidTo = string.Empty;
    }

    public TextTypeSdmx(XmlNode nodeArtefact, XmlNamespaceManager nsmgr, bool fillEmptyLang)
    {
        Init();

        if (nodeArtefact != null)
        {
            XmlNode ndValid = nodeArtefact.Attributes.GetNamedItem("validFrom");
            if (ndValid != null)
                ValidFrom = ndValid.Value;
            ndValid = nodeArtefact.Attributes.GetNamedItem("validTo");
            if (ndValid != null)
                ValidTo = ndValid.Value;

            XmlNode ndFinal = nodeArtefact.Attributes.GetNamedItem("isFinal");
            if (ndFinal != null)
                IsFinal = ndFinal.Value.ToLower() == "true";

            ExtractInternationalized("structure:Name", nodeArtefact, nsmgr, fillEmptyLang);

        }
    }

    private void ExtractInternationalized(string queryTag, XmlNode nodeArtefact, XmlNamespaceManager nsmgr, bool fillEmptyLang)
    {
        int i = 0;
        foreach (string lg in Manager.Instance.SupportedLanguages)
        {
            string query = string.Format("./{1}[@xml:lang='{0}']", lg, queryTag);
            XmlNodeList nodeList = nodeArtefact.SelectNodes(query, nsmgr);
            if (nodeList.Count > 0)
                arrText[i] = nodeList[0].InnerText;
            ++i;
        }

        // Maybe unspecified lang valid for all ?
        if (AllEmpty())
        {
            // Try with no language type
            string query = string.Format("./{0}[not(@xml:lang)]", queryTag);
            XmlNodeList nodeList = nodeArtefact.SelectNodes(query, nsmgr);
            if (nodeList.Count > 0)
                ArrTextInit(nodeList[0].InnerText);
        }

        // If requested fill missing languages
        if (fillEmptyLang)
            for (i = 0; i < arrText.Length; i++)
                if (arrText[i].Length == 0)
                    arrText[i] = FirstFilled();


    }

    #endregion

    #region Internal Methods

    /// <summary>Default all texts</summary>
    private void ArrTextInit(string val)
    {
        for (int i = 0; i < arrText.Length; i++)
            arrText[i] = val;
    }

    /// <summary>Check if text exist in at least one language </summary>
    /// <returns>True if none</returns>
    private bool AllEmpty()
    {
        bool all = true;
        for (int i = 0; i < arrText.Length; i++)
            if (arrText[i].Length > 0)
            {
                all = false;
                break;
            }
        return all;
    }

    /// <summary>get a filled text</summary>
    /// <returns>First filled lang or question mark if nothing available</returns>
    private string FirstFilled()
    {
        string first = "?";
        for (int i = 0; i < arrText.Length; i++)
            if (arrText[i].Length > 0)
            {
                first = arrText[i];
                break;
            }

        return first;
    }

    #endregion

    #region MetadataSet Extractor

    public bool ExtractFromMetadataSet(XmlNode nodeAnnot, XmlNamespaceManager nsmgr, string idRequest, string agencyIdRequest, string versionRequest)
    {
        bool foundFullId = false;  

        // The node transmitted is the Annotation of Type "setID"
        XmlNode nodeId = nodeAnnot.SelectSingleNode("./common:AnnotationTitle", nsmgr);
        string fullId = nodeId != null ? nodeId.InnerText : string.Empty;
        ArtefactPrimaryKey artpk = new ArtefactPrimaryKey("metadatasets", fullId);
        if (artpk.IsValid && artpk.Id == idRequest && artpk.AgencyId == agencyIdRequest && artpk.Version == versionRequest)
        {
            // The parent of the parent is the metadataset node
            XmlNode nodeMetaSet = nodeAnnot.ParentNode.ParentNode;

            // Get optional Valid From / to
            XmlNode ndValidity = nodeMetaSet.Attributes.GetNamedItem("validFromDate");
            if (ndValidity != null)
                ValidFrom = ndValidity.Value;
            ndValidity = nodeMetaSet.Attributes.GetNamedItem("validToDate");
            if (ndValidity != null)
                ValidTo = ndValidity.Value;

            // Get optional isFinal
            // The parent  is the AnnotationList node
            XmlNode nodeFinal = nodeAnnot.ParentNode.SelectSingleNode("./common:Annotation[common:AnnotationType='setIsFinal']", nsmgr);
            if (nodeFinal != null)
            {
                XmlNode ndIsFinal = nodeFinal.SelectSingleNode("./common:AnnotationTitle", nsmgr);
                if (ndIsFinal != null)
                    IsFinal = ndIsFinal.InnerText.ToLower() == "true";
            }

            ExtractInternationalized("genericmetadata:Name", nodeMetaSet, nsmgr, false);

            foundFullId = true;
        }


        return foundFullId;
    }

    #endregion
}
